package com.hww.common.util;

import android.util.Log;

import java.net.NetworkInterface;
import java.util.Collections;
import java.util.List;

/**
 * @author hww
 * @date 2019-07-04.
 * email：
 * description：
 */
public class MacUtil {

    private static final String NETWORK_WLAN = "wlan0";
    private static final String NETWORK_ETH = "eth0";

    /**
     * 获取MAC,先获取wifi，失败后在获取以太网 返回String
     *
     * @return
     */
    public static String getMAC() {
        String mac;
        mac = getMacAddress(NETWORK_WLAN);
        if (null == mac) {
            mac = getMacAddress(NETWORK_ETH);
        }
        if (null == mac) {
            mac = "02:00:00:00:00:00";
        }
        return mac;
    }

    /**
     * 获取MAC,先获取wifi，失败后在获取以太网 返回Byte
     *
     * @return
     */
    public static byte[] getMACByte() {
        byte[] mac;
        mac = getMacAddressByte(NETWORK_WLAN);
        if (null == mac) {
            mac = getMacAddressByte(NETWORK_ETH);
        }
        if (null == mac) {
            mac = new byte[6];
        }
        return mac;
    }

    private static String getMacAddress(String netWork) {
        try {
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface ntwInterface : interfaces) {

                //之前是p2p0，修正为wlan   wlan0  eth0
                if (ntwInterface.getName().equalsIgnoreCase(netWork)) {
                    byte[] byteMac = ntwInterface.getHardwareAddress();
                    if (byteMac == null) {
                        // return null;
                    }
                    StringBuilder strBuilder = new StringBuilder();
                    for (int i = 0; i < byteMac.length; i++) {
                        strBuilder.append(String.format("%02X:", byteMac[i]));
                    }
                    if (strBuilder.length() > 0) {
                        strBuilder.deleteCharAt(strBuilder.length() - 1);
                    }
                    return strBuilder.toString();
                }
            }
        } catch (Exception e) {
            Log.d("hww", e.getMessage());
        }
        return null;
    }

    private static byte[] getMacAddressByte(String netWork) {
        try {
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface ntwInterface : interfaces) {

                if (ntwInterface.getName().equalsIgnoreCase(netWork)) {
                    //之前是p2p0，修正为wlan
                    byte[] byteMac = ntwInterface.getHardwareAddress();
                    if (null != byteMac) {
                        return byteMac;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
